07. Collections - List

List

035ND C01 L01 A08 LIST

One problem with array is, once the size is defined, you will have to stick with the size. If you have an integer array like

A[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 

And the statement below will result in a run-time exception.

A[10] = 10;

Therefore, if you need your array to have a flexible size like List. In Java List is an interface, and ArrayList and LinkedList are two common implementation for List. The differences between ArrayList and LinkedList are ArrayList uses dynamic array where LinkedList uses a doubly linked list to store elements. I will detail the differences next.

Please take a look at their apis, and see if you can solve the quizzes and coding problems on your own.

Resources:

ArrayList: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

LinkedList: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

List Quiz 1

ArrayList<String> list = new ArrayList<String>() ;
list.add( "Andy" );
list.add( "Bart" );
list.add( "Carl" );
list.add( "Doug" );
list.add( "Elmo" );

Which of the following will change the list so that it looks like:

  • Andy
  • Bart
  • Carl
  • Doug
  • Oscar
  • Elmo
SOLUTION: list.add( 4, "Oscar" )

List Quiz 2

What does poll method do in LinkedList?

SOLUTION: Return the first element, and remove it from the linkedlist

List Coding Question

Task Description:

Please complete the coding exercise for List.

Give a list of strings, all in lowercase, and all start with an alphabet character, please group them based on their first character. If the first character is a, group them in a list 0. If the first character is ‘b’, group them in a list 1; other characters, group them in a list 2.

Example1 : input: {“bcd”, “abc”, “cde”}, output: [{“abc”}, {“bcd”}, {“cde”}]

Example2: Input: List: {“abc”, “bcd”, “bbb”, “ace”, “snb”, “aaaa”, “bbbbb”, “eeee”}
Output: [{“abc”, “ace”, “aaaa”}, {“bcd”, “bbb”, “bbbb”}, {“snb”, “eeee”}]

public static List<String>[] groupString(List<String> input) {
}
Task List: